<template>
  <view class="balance-detail">
    
    <!-- 筛选栏 -->
    <view class="filter-tabs">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index"
        :class="['tab-item', currentTab === index ? 'active' : '']"
        @click="switchTab(index)"
      >
        {{ tab }}
      </view>
    </view>

    <!-- 储值记录列表 -->
    <scroll-view scroll-y class="balance-list">
      <block v-for="(monthGroup, month) in balanceData" :key="month">
        <!-- 月份标题 -->
        <view class="month-title">{{ month }}</view>
        
        <!-- 该月的储值记录 -->
        <view 
          class="balance-item"
          v-for="(item, index) in monthGroup"
          :key="index"
        >
          <view class="item-left">
            <text class="item-title">{{ item.title }}<text v-if="item.orderNo">(订单：{{ item.orderNo }})</text></text>
            <text class="item-time">{{ item.time }}</text>
          </view>
          <view 
            class="item-amount"
            :class="item.amount > 0 ? 'plus' : 'minus'"
          >{{ item.amount > 0 ? '+' : '-'}}¥{{ Math.abs(item.amount).toFixed(2) }}</view>
        </view>
      </block>
    </scroll-view>
  </view>
</template>

<script>
	import{listBalance}from'@/api/balance.js'
export default {
  data() {
    return {
      tabs: ['全部', '储值', '消费'],
      currentTab: 0,
	  userId: this.$store.state.user.userId,
      rawBalanceData: {}, // 存储原始格式化后的数据
      balanceData: {
        
      }
    }
  },
  onShow() {
  	this.listBalance()
  },
  methods: {
    navigateBack() {
      uni.navigateBack()
    },
    switchTab(index) {
      this.currentTab = index
      this.filterBalanceByTab()
    },
	
	listBalance(){
		listBalance({userId:this.userId}).then(res=>{
			console.log(res)
			this.rawBalanceData = this.formatBalanceData(res.rows)
			this.filterBalanceByTab()
		}).catch(err => {
			console.error('获取储值记录失败:', err)
			// 使用模拟数据
			this.rawBalanceData = this.formatBalanceData(this.getMockData())
			this.filterBalanceByTab()
		})
	},

	// 模拟数据
	getMockData() {
		
	},

	// 格式化储值数据，按月份分类
	formatBalanceData(rawData) {
		if (!rawData || !Array.isArray(rawData)) {
			return {}
		}

		const monthGroups = {}
		
		rawData.forEach(item => {
			// 解析changeTime字段，假设格式为 "2024-12-15 14:30:00" 或类似格式
			const changeTime = item.changeTime
			if (!changeTime) return
			
			// 提取年月信息
			const date = new Date(changeTime)
			const year = date.getFullYear()
			const month = date.getMonth() + 1 // getMonth() 返回0-11，需要+1
			const monthKey = `${year}年${month.toString().padStart(2, '0')}月`
			
			// 格式化单条记录
			const formattedItem = {
				title: item.balanceType, // 根据实际字段名调整
				time: this.formatDateTime(changeTime),
				amount: parseFloat(item.changeAmount || 0), // 根据实际字段名调整
				orderNo: item.orderNumber || '' // 如果有订单号
			}

			// 根据changeType转换显示文本
			if(formattedItem.title==='0'){
				formattedItem.title='消费'
			}else if(formattedItem.title==='1'){
				formattedItem.title='退款'
			}else if(formattedItem.title==='2'){
				formattedItem.title='充值'
			}else if(formattedItem.title==='33'){
				formattedItem.title='中台订单消耗 '
			}else if(formattedItem.title==='34'){
				formattedItem.title='中台订单退款'
			}else if(formattedItem.title==='35'){
				formattedItem.title='中台储值充值'
			}else if(formattedItem.title==='36'){
				formattedItem.title='中台储值退款'
			}
			
			// 按月份分组
			if (!monthGroups[monthKey]) {
				monthGroups[monthKey] = []
			}
			monthGroups[monthKey].push(formattedItem)
		})
		
		// 对每个月的数据按时间倒序排列
		Object.keys(monthGroups).forEach(month => {
			monthGroups[month].sort((a, b) => new Date(b.time) - new Date(a.time))
		})
		
		// 对月份进行排序（最新的月份在前）
		const sortedMonthGroups = {}
		Object.keys(monthGroups)
			.sort((a, b) => {
				// 解析年月进行比较
				const parseMonth = (monthStr) => {
					const match = monthStr.match(/(\d{4})年(\d{2})月/)
					if (match) {
						return new Date(parseInt(match[1]), parseInt(match[2]) - 1)
					}
					return new Date()
				}
				return parseMonth(b) - parseMonth(a)
			})
			.forEach(month => {
				sortedMonthGroups[month] = monthGroups[month]
			})
		
		return sortedMonthGroups
	},

	// 格式化日期时间显示
	formatDateTime(dateTimeStr) {
		if (!dateTimeStr) return ''
		
		const date = new Date(dateTimeStr)
		const year = date.getFullYear()
		const month = (date.getMonth() + 1).toString().padStart(2, '0')
		const day = date.getDate().toString().padStart(2, '0')
		const hours = date.getHours().toString().padStart(2, '0')
		const minutes = date.getMinutes().toString().padStart(2, '0')
		
		return `${year}-${month}-${day} ${hours}:${minutes}`
	},

	// 根据tab筛选储值数据
	filterBalanceByTab() {
		if (!this.rawBalanceData || Object.keys(this.rawBalanceData).length === 0) {
			this.balanceData = {}
			return
		}

		const filteredData = {}
		
		Object.keys(this.rawBalanceData).forEach(month => {
			const monthData = this.rawBalanceData[month]
			let filteredMonthData = []
			
			switch(this.currentTab) {
				case 0: // 全部
					filteredMonthData = monthData
					break
				case 1: // 储值
					filteredMonthData = monthData.filter(item => item.amount > 0)
					break
				case 2: // 消费
					filteredMonthData = monthData.filter(item => item.amount < 0)
					break
				default:
					filteredMonthData = monthData
			}
			
			// 只有当该月有数据时才添加到结果中
			if (filteredMonthData.length > 0) {
				filteredData[month] = filteredMonthData
			}
		})
		
		this.balanceData = filteredData
	}
	
  }
}
</script>

<style>
.balance-detail {
  min-height: 100vh;
  background: #f5f5f5;
}

.nav-bar {
  display: flex;
  align-items: center;
  height: 44px;
  padding: 0 15px;
  background: #fff;
  position: relative;
}

.back-icon, .right-icon {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.title {
  flex: 1;
  text-align: center;
  font-size: 17px;
  font-weight: 500;
}

.filter-tabs {
  display: flex;
  background: #fff;
  padding: 12px 0;
  margin-bottom: 10px;
}

.tab-item {
  flex: 1;
  text-align: center;
  font-size: 14px;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #333;
  font-weight: 500;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 50%;
  transform: translateX(-50%);
  width: 20px;
  height: 2px;
  background: #FFB610;
  border-radius: 1px;
}

.balance-list {
  height: calc(100vh - 100px);
}

.month-title {
  padding: 10px 15px;
  font-size: 14px;
  color: #000;
}

.balance-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  background: #fff;
  margin-bottom: 10px;
  margin-left: 12px;
  margin-right: 12px;
}

.item-left {
  display: flex;
  flex-direction: column;
}

.item-title {
  font-size: 15px;
  color: #333;
  margin-bottom: 5px;
}

.item-time {
  font-size: 12px;
  color: #999;
}

.item-amount {
  font-size: 16px;
  font-weight: 500;
}

.item-amount.plus {
  color: #FFB610;
}

.item-amount.minus {
  color: #333;
}
</style>
